var default_chat_value = "Say something";
var bigBlindPosition;
var chip1 = "<img src='img/1chip.png' class='1chip_image' alt='10' width='30' height='26' />";
var chip2 = "<img src='img/2chip.png' class='2chip_image' alt='20' width='30' height='26' />";
var chip3 = "<img src='img/3chip.png' class='3chip_image' alt='30' width='30' height='26' />";
var chip4 = "<img src='img/4chip.png' class='4chip_image' alt='40' width='30' height='26' />";
var chip5 = "<img src='img/5chip.png' class='5chip_image' alt='50' width='30' height='26' />";
var chip6 = "<img src='img/6chip.png' class='6chip_image' alt='60' width='30' height='26' />";
$('document').ready(function() {
	chatSocket.init();
	//chat box bindings
	$('#chat_field').val(default_chat_value);
	$('#chat_field').click(function() {if ($(this).val() == default_chat_value) $(this).val('');});
	$('#chat_field').blur(function() {if ($(this).val() == '') $(this).val("Say something");});
	$('#chat_send').click(function(){updateChat();});
	$('#chat_field').bind('keypress', function(e) {
		var code = (e.keyCode ? e.keyCode : e.which);		
		if(code == 13) updateChat();
	});	
	//button bindings
	$('#new_game_button').click(function(){if (confirm("Are you sure?")) restartGame();});
	$('#fold_button').click(function() {doFold();});
	$('#raise_button').click(function() {doRaise();});
	$('#call_button').click(function() {doCall();});
	//initial actions on page load
	$('.dealer').hide();
	$('#footer_buttons').hide();
	getGame();
});

function updateChat() { //add persons message to chat box
	if ($('#chat_field').val() != '') {
		var new_row = $('#chat_field').val();
		$('#chat_field').val('');
		addToChat(new_row);
	} else alert("Please write something first.");
	return false;
}

function addToChat(message) { //add lines to chat box
	chatSocket.writeToScreen(message);
}

function getGame() { //get initial scores, blinds, positions
	$.getJSON('game', {action:"get_game"},function(data) {		
		updateAllPlayers(data);		
	});
}

function clearBoard() {
	$("span[id^=chips_]").html('');
	$("span[id^=dealer_]").hide();
	$("div.player_active").removeClass('player_active');
	$('div.hascards').removeClass('hascards');
	$('img[id^=flop_]').hide().attr({
		  src: 'img/card_back.png',
		  width: '56',
		  height: '60'
		}).show();
	$('span[id^=player_status_]').html('waiting');
	first_card_postition = 0;
	dealt_cards = 0;
	player_count = 0;
	current_response = null;
	getGame();
}

function restartGame() { //set initial scores, randomize positions
	$('div#new_game_button').hide();
	$('img#new_game_loading_indicator').show();
	$.getJSON('game',{action:"restart_game"}, function(data) {
		addToChat("Started new game");		
	});	
	location.reload();
}

function updateAllPlayers(data) { //draw player scores, blinds, statuses
	var current_data, name;	
	$('span[id^=player_score_]').each(function() {
		current_data = data[$(this).attr('id')];
		if ($(this).html() != current_data) {
			name = $('span#player_'+($(this).attr('id')).charAt($(this).attr('id').length-1)+'_name').html();
			addToChat(name+" has score "+current_data);
			$(this).html(data[$(this).attr('id')]);
		}
	});
	$('#dealer_'+data['dealer_position']).show();
	addToChat('Player'+data['dealer_position']+' is the dealer');
	if (parseInt(data['dealer_position']) == 9) {
		$('#chips_0').html(chip1);
		addToChat('Player10 is the small blind');
		$('#chips_1').html(chip2);
		bigBlindPosition = 1;
		addToChat('Player1 is the big blind');		
	} else if(parseInt(data['dealer_position']) == 8) {
		$('#chips_9').html(chip1);
		addToChat('Player9 is the small blind');
		$('#chips_0').html(chip2);
		bigBlindPosition = 0;
		addToChat('Player10 is the big blind');	
	} else {
		$('#chips_'+(parseInt(data['dealer_position'])+1)).html(chip1);
		addToChat('Player'+(parseInt(data['dealer_position'])+1)+' is the small blind');
		$('#chips_'+(parseInt(data['dealer_position'])+2)).html(chip2);
		bigBlindPosition = parseInt(data['dealer_position'])+2;
		addToChat('Player'+(parseInt(data['dealer_position'])+2)+' is the big blind');
	}
	first_card_position = (parseInt(data['dealer_position']) == 9) ? 0 : (parseInt(data['dealer_position'])+1);
	player_count = parseInt(data['player_count']);
	current_response = data;
	dealcards(first_card_position);	
}
var first_card_postition = 0;
var dealt_cards = 0;
var player_count = 0;
var current_response;

function dealcards(i) {
	if (dealt_cards >= player_count) initPositions();
	else {
		$('div#player_'+i).hide().addClass('hascards').fadeIn(300, function(){		
			if (i == 0) addToChat('Player10 has 2 cards');
			else addToChat('Player'+i+' has 2 cards');
			dealt_cards++;
			if (i == 9) dealcards(0);
			else dealcards(i+1);
		});
	}
}

function initPositions() {
	data = current_response;
	$('#player_'+data['person_position']).hide().addClass('person').fadeIn(100, function() {
		$('#player_'+data['person_position']).removeClass('hascards');
		$('div#person_cards').html('<img src="cards/'+data['person_card1']+'.png" width="50" height="63"/>'+'<img src="cards/'+data['person_card2']+'.png" width="50" height="63" />');
		addToChat('Your cards are:'+data['person_card1']+' & '+data['person_card2']);
		$('#person_cards').hide().fadeIn(1000,function() {
			$('#player_'+data['next_position']).hide().addClass('player_active').fadeIn(700, function() {
				$('#pot').html(data['pot']);
				addToChat("Current pot is "+data['pot']);
				addToChat("The next one to act is Player "+(data['next_position'] == 0 ? 10 : data['next_position']));
				if (data['person_position'] == data['next_position']) {
					$('#call_button').html('<p>Call '+data['big_blind']+'</p>');
					$('#footer_buttons').fadeIn('slow');					
				}
				else getNextPlayerAction();
			});			
		});		
	});
}


function getNextPlayerAction() {
	data = current_response;
	if (data['person'] == 'true') {
		if (data['person_call'] == 0) {
			$('#call_button').html("<p>Check</p>");
		} else {
			$('#call_button').html("<p>Call " + data['person_call'] + '</p>');
		}
		$('div#footer_buttons').fadeIn('slow');
	} else {
		$.getJSON('game', {action:"get_next_move"},function(data) {
			current_response = data;
			updateNextPlayer();
		});
	}
}

function showWinner() {
	data = current_response;
	for (var i = 0; i < 10; i++) {
		if (typeof data['player_score_'+i] != "undefined") {
			$('#player_card1_'+i).html('<img src="cards/'+data['player_card1_'+i]+'.png" width="50" height="63"/>').show();
			$('#player_card2_'+i).html('<img src="cards/'+data['player_card2_'+i]+'.png" width="50" height="63"/>').show();
			addToChat("Player"+i+" shows : "+data['player_card1_'+i]+" and "+data['player_card2_'+i]);
		}
	}	
	showEndingStatuses(0);
}

function showEndingStatuses(i) {
	var data = current_response;	
	if (i >= player_count) {
		$('#pot').html('0');
		addToChat("Player"+data['winner_position']+" takes the pot, his score is now "+data['player_score_'+data['winner_position']]);
		$('#player_card1_'+data['winner_position']).fadeOut('slow', function() {
			$('#player_card2_'+data['winner_position']).fadeOut('slow', function() {
				$('#player_score_'+data['winner_position']).hide().html(data['player_score_'+data['winner_position']]).fadeIn(2000, function() {
					clearBoard();
				});				
			});
		});
	} else if (typeof data['player_score_'+i] != "undefined") {		
		$('#player_status_'+i).html(data['player_score_'+i]);
		$('#player_status_'+i).hide().html(data['player_status_'+i]).fadeIn(300, function() {
			if (data['player_status_'+i] == "loser") {
				$('#player_score_'+data['winner_position']).html(data['player_score_'+i]);
				$('#player_card1_'+i).fadeOut('slow', function() {					
					$('#player_card2_'+i).fadeOut('slow', function() {						
						showEndingStatuses(i+1);
					}).html('');
				}).html('');
			} else showEndingStatuses(i+1);
		});
	} else {
		showEndingStatuses(i+1);
	}
}

function doFlop() {
	data = current_response;	
	$('span[id^=player_score_]').each(function() {$(this).html(data[$(this).attr('id')]);});	
	$('span[id^=player_status_]').each(function() {	$(this).html(data[$(this).attr('id')]);	});
	$("span[id^=chips_]").html('');
	if (typeof data['card1'] != 'undefined') {
		$('#flop_1').hide().attr('src','cards/'+data['card1']+'.png').fadeIn('slow', function() {
			$('#flop_2').hide().attr('src','cards/'+data['card2']+'.png').fadeIn('slow', function() {
				$('#flop_3').hide().attr('src','cards/'+data['card3']+'.png').fadeIn('slow', function() {
					getNextPlayerAction();
				});
			});
		});
	} else if(typeof data['card4'] != 'undefined') {
		$('#flop_4').hide().attr('src', 'cards/'+data['card4']+'.png').fadeIn(1000, function() {
			getNextPlayerAction();
		});
	} else if(typeof data['card5'] != 'undefined') {
		$('#flop_5').hide().attr('src', 'cards/'+data['card5']+'.png').fadeIn(1000, function() {
			getNextPlayerAction();
		});
	} else alert('Unexpected error occured, please restart the game.');
}

function updateNextPlayer() {
	data = current_response;
	if(typeof data['over'] != undefined && data['over'] == "true") {
		showWinner();
		return;
	}
	var state = data['status'];
	var pos = data['position'];
	$('#player_score_'+pos).html(data['score']);		
	$('#player_status_'+pos).hide().html(state).fadeIn(800,function(){
			$('#player_'+pos).removeClass('player_active');
			if (state == 'fold') {
				$('#player_'+pos).hide().removeClass('hascards').fadeIn('slow',function(){
					if (parseInt(pos) == 0) pos = 10;
					addToChat('Player'+pos+' folded');
					$('#player_'+data['next_position']).addClass('player_active');
					if (data['flop'] == 'true') doFlop();
					else getNextPlayerAction();
				});				
			} else if (state == 'check'){
				if (parseInt(pos) == 0) pos = 10;
				addToChat('Player'+pos+' checked');
				$('#player_'+data['next_position']).addClass('player_active');
				if (data['flop'] == 'true') doFlop();
				else if(typeof data['over'] != undefined && data['over'] == "true") {
					showWinner();
					return;
				}
				else getNextPlayerAction();
			} else if (state == 'call') {				
				if ($("img.4chip_image").length>0) $('#chips_'+pos).html(chip4);
				else $('#chips_'+pos).html(chip2);
				if (parseInt(pos) == 0) pos = 10;
				addToChat('Player '+pos+' called');				
				$('#pot').html(data['pot']).hide().fadeIn(400,function(){
					addToChat('Pot is now '+data['pot']);
					$('#player_'+data['next_position']).addClass('player_active');
					if (data['flop'] == 'true') doFlop();
					else getNextPlayerAction();
				});
			} else if (state == 'raise'){
				$('#chips_'+pos).html(chip4);
				if (parseInt(pos) == 0) pos = 10;
				addToChat('Player '+pos+' raised');				
				$('#pot').html(data['pot']).hide().fadeIn(400,function(){
					addToChat('Pot is now '+data['pot']);
					$('#player_'+data['next_position']).addClass('player_active');
					if (data['flop'] == 'true') doFlop();
					else getNextPlayerAction();
				});
			}else {
				$('#player_'+data['next_position']).addClass('player_active');
				if (data['flop'] == 'true') doFlop();
				else getNextPlayerAction();
			}			
		
	});		
}

function doCall() { //persons call action
	$('div#footer_buttons').hide();	
	$.getJSON('game', {action:"person_call"},function(data) {
		current_response = data;
		if (data['flop'] == 'true') doFlop();		
		else updateNextPlayer();
	});
}
function doFold() { //persons fold action
	$('div#footer_buttons').hide();
	addToChat('You folded');
	$.getJSON('game', {action:"person_fold"},function(data) {
		current_response = data;
		if (data['flop'] == 'true') doFlop();		
		else updateNextPlayer();
	});
}
function doRaise() { //persons raise action
	$('div#footer_buttons').hide();
	addToChat('You raised');		
	$.getJSON('game', {action:"person_raise"},function(data) {		
		current_response = data;
		if (data['flop'] == 'true') doFlop();		
		else updateNextPlayer();
	});
}